<template>
    <!-- 规格选择 -->
    <div class="popup-container" @click="closePopup">
        <div class="spec-popup popup no-padding bottom" @click.stop>

            <div class="spec-content white-bg">
                <div class="info-wrap clearfix">
                    <!-- 去掉.stop情况下有意外情况发生，暂时无解 -->
                    <i class="icon close-icon" @click.stop="closePopup">&#xe618;</i>
                </div>
                <div v-if="manage" class="sku-container">

                    <div v-for="(wrap, i) in specList"
                        :key="i"
                        class="spec-list-wrap">
                        <div class="name text-normal">{{ wrap.name }}</div>
                        <div v-for="(spec, j) in wrap.list"
                            :key="j"
                            class="spec-wrap">
                            <div class="btn btn-mobile btn-spec btn-normal border wider"
                                :class="{active: selected[wrap.key] == spec, 'disabled': manage.map[wrap.key][spec].quantity < minQuantity || !manage.map[wrap.key][spec].enable}"
                                :is-disabled="manage.map[wrap.key][spec].quantity < minQuantity || !manage.map[wrap.key][spec].enable"
                                @click="onClickSpec(wrap.key, spec)">
                                {{ spec }}
                            </div>
                        </div>
                        <div class="after-line-1"></div>
                    </div>

                    <div class="name text-normal" @click.stop v-if="currentSpecification != null && countVisible">
                        <span class="buy-num-tips">购买数量<span v-if="isSeckill">(每人限购1件)</span></span>
                        <span class="fr">
                            <Counter v-model="mutableCount"
                                :min="minQuantity"
                                :change-able="true">
                            </Counter>
                        </span>
                    </div>
                </div>

                <!-- 底部按钮 -->
                <div class="absolute-btn-wrap">
                    <span class="price">
                       总计: ￥{{price}}
                        <span v-if="rebate" class="price__rebate">{{rebateLabel}} <span class="color-red">￥{{rebate}}</span></span>
                    </span>
                    <div class="btn btn-mobile btn-large btn-white-red btn-block btn-rect font-medium"
                        @click.stop="onClickPrimary">
                        确认规格
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {
    mapState,
} from 'vuex';
import {
    isUndef,
    formatPrice,
    makeMap,
    currency,
} from '@/lib/utils';
import Counter from '@/features/product/counter.vue';
import SpecManage from '@/lib/script/spec';
import store from '@/store';

export default {
    name: 'SpecPopup',
    components: {
        Counter,
    },
    props: {
        /** 数据详情 */
        productDetail: {
            type: Object,
        },
        /** 当前的规格id，允许不传 */
        specId: {
            type: Number,
        },
        /** 所要求的最小库存 */
        minQuantity: {
            default: 1,
        },
        count: {
            type: Number,
        },
        /** 确认 */
        primaryButtonText: {
            type: String,
            default: '确认',
        },
        /** 当前选中的数量 */
        currentQuantity: {
            default: 1,
        },
        countVisible: {
            type: Boolean,
        },
    },
    data() {
        return {
            /** 管理对象 */
            manage: null,
            /** 购买数量控制 */
            mutableCount: 1,
            /** 当前选中的规格，可能是null */
            currentSpecification: null,
        };
    },
    computed: {
        ...mapState({
            userBasicInfo: state => state.user.basicInfo,
        }),
        /** 所有需要展示的规格 */
        specList() {
            const manage = this.manage;
            return manage ? manage.meta.map((item) => ({
                key: item.key,
                name: item.name,
                list: item.list,
            })) : [];
        },
        /** 所展示的价格 */
        price() {
            if (!this.manage || !this.productDetail) {
                return 0;
            }
            const spec = this.currentSpecification;
            if (!spec) {
                return 0;
            }
            const price = this.productDetail.getPrice(spec ? spec.id : null);

            if (!price) {
                return '暂无数据';
            } else {
                const min = price.min || 0;
                let minResult = null;
                for (let item of this.discount.full_reduction || []) {
                    if (min >= item.limit) {
                        if (!minResult) {
                            minResult = item;
                        } else if (item.abatement > minResult.abatement) {
                            minResult = item;
                        }
                    }
                }
                for (let item of (this.discount.discount || [])) {
                    if (min >= item.limit) {
                        if (!minResult) {
                            minResult = {
                                id: item.id,
                                title: item.title,
                                limit: item.limit,
                                abatement: item.ratio,
                            };
                        }
                    }
                }

                const max = price.max || 0;
                let maxResult = null;
                for (let item of this.discount.full_reduction || []) {
                    if (max >= item.limit) {
                        if (!maxResult) {
                            maxResult = item;
                        } else if (item.abatement > maxResult.abatement) {
                            maxResult = item;
                        }
                    }
                }
                for (let item of (this.discount.discount || [])) {
                    if (max >= item.limit) {
                        if (!maxResult) {
                            maxResult = {
                                id: item.id,
                                title: item.title,
                                limit: item.limit,
                                abatement: item.ratio,
                            };
                        }
                    }
                }

                return formatPrice({
                    min: min * this.mutableCount,
                    max: max * this.mutableCount,
                });
            }
        },
        // /** 当前选中的规格，可能是null */
        // currentSpecification() {
        //     if (!this.manage) {
        //         return null;
        //     }
        //     const temp = this.manage.getSelectedSpecification();
        //     console.log('specPopup get currentSpecification', temp);
        //     return null;
        // },
        /** 当前的选中数据 */
        selectData() {
            if (!this.manage) {
                return;
            }

            const selectedValues = [];
            const emptyNames = [];
            const specMap = makeMap(this.manage.meta, 'key', (row) => row.name);
            for (const wrap of this.manage.meta) {
                if (this.manage.selected[wrap.key]) {
                    selectedValues.push(this.manage.selected[wrap.key]);
                } else {
                    emptyNames.push(specMap[wrap.key]);
                }
            }
            return {
                selectedValues,
                emptyNames,
            };
        },
        selected() {
            return this.manage ? this.manage.selected : {};
        },
        rebateLabel() {
            const list = [
                '返利',
                '推荐返还',
                '推荐分红',
                '推荐提成',
            ];
            return this.userBasicInfo ? list[this.userBasicInfo.level] : '';
        },
        /** 特定规格返利 */
        rebate() {
            const basicInfo = this.userBasicInfo;
            const spec = this.currentSpecification;
            if (!basicInfo || !spec || !this.productDetail) {
                return null;
            }
            // 只有返利会员进行限制
            if (basicInfo.level === 1) {
                const shops = store.state.user.memberShopList || [];
                const find = shops.find((shop) => shop.shop_id === this.productDetail.shop_id);
                if (!find) {
                    return null;
                }
            }

            const key = [ this.productDetail.id, spec.id, ].join('_');
            const ruleList = store.state.good.rebateRule[key] || [];
            if (!ruleList || ruleList.length === 0) {
                return null;
            }
            const rule = ruleList[0];
            const level = basicInfo.level;
            if (level === 1) {
                return currency(rule.level1_rebate);
            } else if (level === 2) {
                return currency(rule.level2_rebate);
            } else if (level === 3) {
                return [ currency( store.state.good.checkUser == true? rule.level3_rebate : rule.level4_rebate || 0), currency(rule.level_2_3_rebate || 0), ].join('/');
            }
        },

        discount() {
            return store.state.good.discount[this.productDetail.id] || {
                full_reduction: [],
                discount: [],
                //新增
                gift: [],
                balance: {},

            };
        },
    },
    watch: {
        manage: {
            handler() {
                if (!this.manage) {
                    return null;
                }
                this.currentSpecification = this.manage.getSelectedSpecification() || null;
            },
            // immediate: true,
            deep: true,
        },
        // '$props.currentQuantity'(val) {
        //     this.mutableCount = val;
        // },
        visible(val) {
            this.$emit('input', val);
            // 保证在每次显示的时候都是正确的specId所对应的数据
            this.selectSpec();
        },
        '$props.specId'() {
            this.selectSpec();
        },
        productDetail() {
            // tip: 当商品更新，那么需要更新manage
            this.createSpecManage();
        },
        currentSpecification(spec) {
            if (spec && this.productDetail) {
                // 加载返利数据
                store.dispatch('good/getRebateRule', {
                    productId: this.productDetail.id,
                    specId: spec.id,
                });
            }
        },
    },
    methods: {
        /**
         * 关闭弹窗
         */
        closePopup() {
            this.$emit('close');
        },
        /**
         * 选择合适的规格
         */
        selectSpec() {
            if (this.manage && this.specId) {
                const spec = this.productDetail.getSpec(this.specId);
                if (spec && spec.stock >= this.minQuantity) {
                    this.manage.select({
                        ...spec.param,
                    });
                    // this.manage.select({
                    //     attr1: spec.param.attr1,
                    //     attr2: spec.param.attr2,
                    //     attr3: spec.param.attr3,
                    // });
                }
            }
        },
        /**
         * 创建manage
         */
        createSpecManage() {
            if (!this.productDetail || !this.productDetail.specIds) {
                return;
            }
            const manage = new SpecManage({
                minQuantity: this.minQuantity,
            });
            const specList = this.productDetail.specIds.map((specId) => this.productDetail.getSpec(specId));
            const validSpecList = specList.filter((item) => !isUndef(item));
            const attr = this.productDetail.attr;
            validSpecList.forEach((item) => {
                attr.forEach((attr, index) => {
                    const attrKey = 'attr' + (index + 1);
                    if (item.param[attr]) {
                        manage.addSpecQuantity(attrKey, item.param[attr], item.stock);
                    }
                });
            });
            attr.forEach((attr, index) => {
                const attrKey = 'attr' + (index + 1);
                if (attr) {
                    manage.addMeta(attrKey, attr, Object.keys(manage.map[attrKey]));
                }
            });
            validSpecList.forEach((item) => {
                const lineInfo = {
                    quantity: item.stock,
                };
                attr.forEach((attr, index) => {
                    const attrKey = 'attr' + (index + 1);
                    if (item.param[attr]) {
                        lineInfo[attrKey] = item.param[attr];
                        item.param[attrKey] = item.param[attr];
                    }
                });
                manage.buildLine(lineInfo);
                manage.storeSpecMap(item);
            });
            // validSpecList.forEach((item) => {
            //     if (item.param[attr[0]]) {
            //         manage.addSpecQuantity('attr1', item.param[attr[0]], item.stock);
            //     }
            //     if (item.param[attr[1]]) {
            //         manage.addSpecQuantity('attr2', item.param[attr[1]], item.stock);
            //     }
            //     if (item.param[attr[2]]) {
            //         manage.addSpecQuantity('attr3', item.param[attr[2]], item.stock);
            //     }
            // });
            // if (attr[0]) {
            //     manage.addMeta('attr1', attr[0], Object.keys(manage.map.attr1));
            // }
            // if (attr[1]) {
            //     manage.addMeta('attr2', attr[1], Object.keys(manage.map.attr2));
            // }
            // if (attr[2]) {
            //     manage.addMeta('attr3', attr[2], Object.keys(manage.map.attr3));
            // }
            // validSpecList.forEach((item) => {
            //     const lineInfo = {
            //         quantity: item.stock,
            //     };
            //     if (item.param[attr[0]]) {
            //         lineInfo.attr1 = item.param[attr[0]];
            //         item.param.attr1 = item.param[attr[0]];
            //     }
            //     if (item.param[attr[1]]) {
            //         lineInfo.attr2 = item.param[attr[1]];
            //         item.param.attr2 = item.param[attr[1]];
            //     }
            //     if (item.param[attr[2]]) {
            //         lineInfo.attr3 = item.param[attr[2]];
            //         item.param.attr3 = item.param[attr[2]];
            //     }
            //     manage.buildLine(lineInfo);
            //     manage.storeSpecMap(item);
            // });
            this.manage = manage;
            this.selectSpec();
        },
        /**
         * 添加spec
         */
        onClickSpec(key, spec) {
            if (!this.manage) {
                return;
            }
            if (this.manage.map[key][spec].quantity < this.minQuantity || !this.manage.map[key][spec].enable) {
                wx.showToast({
                    title: '库存不足',
                    icon: 'none',
                });
                return;
            }
            this.manage.toggleSpec(key, spec);
        },
        /**
         * 点击确认选择
         */
        onClickSubmit() {
            // 没有初始化使用的信息
            if (!this.manage) {
                return;
            }
            // 如果存在没有选择的规格，进行提示
            let pendingComplete = false;
            for (const row of this.specList) {
                // 没有选择的情况下，进行提示
                if (!this.manage.selected[row.key]) {
                    // todo: 提示
                    wx.showToast({
                        title: `请选择 ${row.name}`,
                        icon: 'none',
                    });
                    pendingComplete = true;
                    break;
                }
            }
            // 需要继续选择
            if (pendingComplete) {
                return;
            }

            // 检查规格库存
            const maxQuantity = this.currentSpecification.stock;

            if (maxQuantity < this.mutableCount) {
                wx.showToast({
                    title: `库存只剩${maxQuantity}份了`,
                    icon: 'none',
                });
                this.mutableCount = maxQuantity;
                return;
            }
            // 没有需要填写的数据
            this.$emit('select', this.currentSpecification, this.mutableCount);
            this.$emit('close');
        },
        /**
         * 提交规格
         */
        onClickPrimary() {
            this.onClickSubmit();
            this.$emit('primary');
        },
    },
    created() {
        this.mutableCount = this.count;
    },
    mounted() {
        this.createSpecManage();
    },
};
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.spec-popup {
    height: 75%;
    padding: 0; // 重置popup的样式
    color: @color-font-1;
    box-sizing: border-box;
    &.no-padding {
        padding-bottom: 0;
    }
    .spec-content {
        position: relative;
        box-sizing: border-box;
        height: 100%;
        padding-bottom: 60px;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        // overflow: scroll;
    }

    #spec-confirm-btn {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
    }

    .name {
        padding: 10px 15px;
        font-size: 14px;
        line-height: 20px;
        color: @color-font-1;
    }
    .desc {
        display: inline-block;
        min-width: 28px;
        margin: 10px 10px 0 0;
        padding: 5 16;
        font-size: 14px;
        border: 1px solid @primary-color;
        background: white;
        color: @primary-color;
        &[disabled] {
            border: 1px dashed #999999;
            background-color: #ffffff;
            color: #999999;
        }
    }
    .close-icon {
        position: absolute;
        display: inline-block;
        top: 17px;
        right: 17px;
        // padding, 5;
        font-size: 17px;
        color: black;
        z-index: 2;
    }
    .sku-container {
        height: 100%;
        overflow-y: scroll;
        -webkit-overflow-scrolling: touch;
    }
    .active {
        color: white;
        background: @primary-color;
    }

    .info-wrap {
        position: relative;
        padding: 20px 14px 0;
        .after-line-1 {
            margin: 20px 0 9px;
            box-sizing: border-box;
        }
    }

    // 每个spec行
    .spec-list-wrap {
        padding: 5px 10px;
        .name {
            padding: 0 5px 10px;
        }
    }
    .after-line-1 {
        border-bottom: 1px solid rgba(242, 242, 242, 1);
    }
    .spec-wrap {
        display: inline-block;
        padding: 5px 5px 9px;
    }
    .absolute-btn-wrap {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        background: @white-color;
        .price {
            flex: 1;
            padding-left: 15px;

            &__rebate {
                display: inline-block;
                padding: 1px 5px;
                margin-left: 5px;
                .text-normal();
            }
        }
    }
    .buy-num-tips {
        line-height: 26px;
    }
}
</style>
